<template>
    <el-main class="cart-container">
        <!-- 商品列表 -->
        <el-table v-loading="listLoading" :data="paginatedData" ref="multipleTable"
            @selection-change="handleSelectionChange" style="width: 100%" :row-key="getKey" class="cart-table">
            <!-- 选择列 -->
            <el-table-column type="selection" :reserve-selection="true" width="80" align="center"></el-table-column>

            <!-- 商品信息列 -->
            <el-table-column prop="goodsName" label="产品名称" min-width="180" show-overflow-tooltip></el-table-column>

            <!-- 价格列 -->
            <el-table-column label="单价" width="120" align="center">
                <template slot-scope="scope">
                    <div class="price-cell">￥{{ scope.row.price.toFixed(2) }}</div>
                </template>
            </el-table-column>

            <!-- 数量选择列 -->
            <el-table-column label="数量" width="160" align="center">
                <template slot-scope="scope">
                    <el-input-number v-model="scope.row.quantity" :min="1" :max="99" size="small"
                        controls-position="right"></el-input-number>
                </template>
            </el-table-column>

            <!-- 商品图片 -->
            <el-table-column label="商品图片" width="160" align="center">
                <template slot-scope="scope">
                    <el-image class="product-thumb" :src="scope.row.goodsPicture"
                        :preview-src-list="[scope.row.goodsPicture]" fit="cover">
                        <div slot="error" class="image-error">
                            <i class="el-icon-picture-outline"></i>
                        </div>
                    </el-image>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
            <el-pagination :current-page.sync="currentPage" :page-size="pageSize" :total="total"
                layout="prev, pager, next, jumper" @current-change="handlePageChange"></el-pagination>
        </div>

        <!-- 底部操作栏 -->
        <div class="cart-action-bar">
            <div class="action-left">
                <el-checkbox v-model="isAllSelected" @change="handleSelectAll"
                    class="select-all-checkbox">全选</el-checkbox>

                <el-button type="text" @click="handleBatchDelete" class="action-btn">删除选中</el-button>

                <el-button type="text" @click="handleMoveToFavorites" class="action-btn">移入收藏</el-button>
                <el-button type="text" @click="selectCoupon" class="action-btn">查看优惠劵</el-button>
            </div>

            <div class="action-right">
                <div class="price-summary">
                    <div class="total-items">
                        已选 <span class="highlight">{{ selectedCount }}</span> 件商品
                    </div>
                    <div class="total-price">
                        总计：<span class="highlight">￥{{ totalPrice.toFixed(2) }}</span>
                    </div>
                    <div class="price-tips">不含运费及服务费</div>
                </div>
                <el-button type="primary" class="checkout-btn" @click="handleCheckout"
                    :disabled="selectedCount === 0">去结算</el-button>
            </div>
        </div>

        <!-- 支付二维码弹窗 -->
        <el-dialog title="扫码支付" :visible.sync="qrDialogVisible" width="30%" center :before-close="handleCloseDialog">
            <div class="qr-code-container">
                <div v-if="qrCodeUrl" class="qr-code-wrapper">
                    <img :src="this.qrCodeUrl" alt="支付二维码">
                    <p class="qr-instruction">请使用支付宝扫描二维码完成支付</p>
                    <p class="qr-amount">支付金额: ￥{{ totalPrice.toFixed(2) }}</p>
                </div>
                <div v-else class="loading-wrapper">
                    <el-button type="primary" :loading="qrLoading">正在生成支付二维码...</el-button>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="qrDialogVisible = false">取消支付</el-button>
            </span>

        </el-dialog>
        <el-dialog title="选择优惠券" :visible.sync="couponDialogVisible" width="600px" center>
            <el-radio-group v-model="selectedCouponId" class="coupon-list">
                <el-radio v-for="coupon in coupons" :key="coupon.id" :label="coupon.id" class="coupon-item"
                    :disabled="isCouponDisabled(coupon)">
                    <div class="coupon-card" :class="couponStatusClass(coupon)">
                        <div class="coupon-header">
                            <span class="amount">
                                <template v-if="coupon.couponType === 1">
                                    ￥{{ coupon.discountAmount }}
                                </template>
                                <template v-else-if="coupon.couponType === 2">
                                    {{ (coupon.discountRate * 10).toFixed(1) }}折
                                </template>
                                <template v-else-if="coupon.couponType === 3">
                                    ￥{{ coupon.discountAmount }}
                                </template>
                            </span>
                            <div class="coupon-type">
                                {{ couponTypeMap[coupon.couponType] }}
                            </div>
                        </div>

                        <div class="coupon-body">
                            <div class="coupon-name">{{ coupon.couponName }}</div>
                            <div class="condition" v-if="coupon.minAmount">
                                满{{ coupon.minAmount }}元可用
                            </div>
                            <!-- <div class="expire">
                                有效期至：{{ dayjs(coupon.endTime).format('YYYY-MM-DD HH:mm') }}
                            </div> -->
                        </div>
                    </div>
                </el-radio>
            </el-radio-group>

            <div slot="footer" class="dialog-footer">
                <el-button @click="couponDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleConfirmCoupon" :disabled="!selectedCouponId">
                    确 定
                </el-button>
            </div>
        </el-dialog>
    </el-main>
</template>

<script>
import { getCartList, batchDeleteItems } from '@/api/user/cart';
import { addOrder } from '@/api/user/order';
import { getCouponByUserId } from '@/api/user/coupon';
import { mapGetters } from 'vuex';
import request from "@/utils/request";
export default {
    data() {
        return {
            couponDialogVisible: false,
            coupons: [], // 优惠券列表
            selectedCouponId: null,
            selectedCoupon: null,
            couponTypeMap: {
                1: '满减券',
                2: '折扣券',
                3: '立减券'
            },

            listLoading: false,
            pageSize: 10,
            currentPage: 1,
            total: 0,
            cartItems: [],
            selectedItems: [],
            qrDialogVisible: false,
            qrCodeUrl: '',
            qrLoading: false,
            currentOrderId: null
        };
    },

    computed: {
        ...mapGetters(['userId']),

        paginatedData() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = this.currentPage * this.pageSize;
            return this.cartItems.slice(start, end);
        },

        selectedCount() {
            return this.selectedItems.length;
        },

        // totalPrice() {
        //     return this.selectedItems.reduce((sum, item) => {
        //         return sum + (item.price * item.quantity);
        //     }, 0);
        // },
        originalTotalPrice() {
            return this.selectedItems.reduce((sum, item) => {
                return sum + (item.price * item.quantity);
            }, 0);
        },

        // 最终优惠后价格
        totalPrice() {
            if (!this.selectedCoupon) return this.originalTotalPrice;

            switch (this.selectedCoupon.couponType) {
                case 1: // 满减券
                    return this.originalTotalPrice >= this.selectedCoupon.minAmount
                        ? this.originalTotalPrice - this.selectedCoupon.discountAmount
                        : this.originalTotalPrice;

                case 2: // 折扣券
                    return this.originalTotalPrice * this.selectedCoupon.discountRate;

                case 3: // 立减券
                    return Math.max(0, this.originalTotalPrice - this.selectedCoupon.discountAmount);

                default:
                    return this.originalTotalPrice;
            }
        },
        isAllSelected: {
            get() {
                return this.selectedItems.length === this.cartItems.length;
            },
            set(value) {
                this.$refs.multipleTable.toggleAllSelection();
            }
        }
    },

    methods: {


        handleSelectionChange(selection) {
            this.selectedItems = selection;
        },

        handleSelectAll() {
            this.$refs.multipleTable.toggleAllSelection();
        },

        async handleBatchDelete() {
            if (this.selectedCount === 0) {
                return this.$message.warning('请选择要删除的商品');
            }
            try {
                await this.$confirm('确定删除选中商品吗？', '提示', { type: 'warning' });
                console.log('this.selectedItems', this.selectedItems);

                await batchDeleteItems(this.selectedItems.map(item => item.id));
                await this.loadCartData();
                this.$message.success('删除成功');
            } catch (error) {
                if (error !== 'cancel') {
                    this.$message.error('删除失败');
                }
            }
        },
        async handleCheckout() {
            if (this.selectedCount === 0) {
                this.$message.warning('请选择要结算的商品');
                return;
            }

            try {
                this.qrLoading = true;
                this.qrDialogVisible = true;
                this.paymentStatus = 'pending'; // 新增支付状态

                const orderItems = this.selectedItems.map(item => ({
                    storeId: item.storeId,
                    quantity: item.quantity,
                    image: item.goodsPicture,
                    goodsId: item.id,
                    price: item.price
                }));

                const type = 'normal';
                const qrRes = await addOrder({
                    orderDTOS: orderItems,
                    moneyCount: this.totalPrice,
                    couponOrder: this.selectedCoupon
                }, type);

                if (!qrRes?.data) {
                    throw new Error('获取支付二维码失败: 响应数据无效');
                }

                this.qrCodeUrl = `${qrRes.data[1]}?x-oss-process=image`;
                this.payOrderId = qrRes.data[0]; // 保存订单ID

                // 开始轮询检查支付状态
                this.startPaymentCheck(type);
            } catch (error) {
                console.error('支付流程出错:', error);
                this.$message.error(error.message || '支付失败，请重试');
                this.resetPaymentState();
            } finally {
                this.qrLoading = false;
            }
        },

        startPaymentCheck(type) {
            const MAX_RETRY = 30;
            let retryCount = 0;

            // 清除可能存在的旧定时器
            if (this.paymentTimer) clearTimeout(this.paymentTimer);

            const checkPayment = async () => {
                try {
                    // 如果弹窗已关闭，停止检查
                    if (!this.qrDialogVisible) return;

                    const { data } = await request({
                        url: `/user/Order/checkOrder/${type}`,
                        method: 'get',
                        params: { payOrderId: this.payOrderId }
                    });

                    if (data) {
                        this.handlePaymentSuccess();

                        return;
                    }

                    if (retryCount++ < MAX_RETRY) {
                        this.paymentTimer = setTimeout(checkPayment, 2000);
                    } else {
                        this.$message.warning('支付超时，请检查支付状态');
                        this.resetPaymentState();
                    }
                } catch (error) {
                    console.error("检查支付状态出错", error);
                    if (retryCount++ < MAX_RETRY) {
                        this.paymentTimer = setTimeout(checkPayment, 2000);
                    } else {
                        this.$message.error('支付状态检查失败，请稍后手动查询');
                        this.resetPaymentState();
                    }
                }
            };

            // 立即开始第一次检查
            this.paymentTimer = setTimeout(checkPayment, 2000);
        },

        handlePaymentSuccess() {
            // 清除定时器
            if (this.paymentTimer) {
                clearTimeout(this.paymentTimer);
                this.paymentTimer = null;
            }

            // 更新状态
            this.paymentStatus = 'success';
            this.$message.success('支付成功');
            this.qrDialogVisible = false;

            // 更新本地用户数据
            const user = JSON.parse(getUser());
            user.carNum -= this.selectedItems.length;
            setUser(JSON.stringify(user));

            // **调用原有方法刷新购物车数据**
            this.loadCartData(); // 触发购物车数据重新加载

            // 跳转页面
            this.$router.push('/orders');
        },

        // 原有购物车数据加载方法
        async loadCartData() {
            try {
                this.listLoading = true;
                const res = await getCartList();
                this.cartItems = res.data.map(item => ({
                    ...item,
                    price: item.price || 0,
                    quantity: item.quantity || 1
                }));
                this.total = this.cartItems.length;
            } catch (error) {
                this.$message.error('加载购物车失败');
            } finally {
                this.listLoading = false;
            }
        },


        // 关闭二维码弹窗时调用
        closeQrDialog() {
            this.resetPaymentState();
            this.qrDialogVisible = false;
        },

        // 重置支付状态
        resetPaymentState() {
            if (this.paymentTimer) {
                clearTimeout(this.paymentTimer);
                this.paymentTimer = null;
            }
            this.paymentStatus = 'idle';
            this.payOrderId = null;
        },
        handleCloseDialog(done) {
            if (this.qrLoading) {
                this.$message.warning('正在生成二维码，请稍候');
                return false;
            }
            done();
        },

        getKey(row) {
            return row.id;
        },

        handleMoveToFavorites() {
            // 移入收藏夹的实现
            this.$message.info('移入收藏功能待实现');
        },

        handlePageChange() {
            // 分页变化处理
        },
        async selectCoupon() {
            try {
                const res = await getCouponByUserId();
                this.coupons = res.data.data;
                console.log('res.data', this.coupons);
                this.couponDialogVisible = true;
                this.selectedCouponId = null;
            } catch (error) {
                this.$message.error('获取优惠券失败');
            }
        },

        // 确认选择优惠券
        handleConfirmCoupon() {
            this.selectedCoupon = this.coupons.find(c => c.id === this.selectedCouponId);
            // this.$emit('coupon-selected', selectedCoupon);
            this.couponDialogVisible = false;
        },

        // 判断优惠券是否可用
        isCouponDisabled(coupon) {
            // 根据业务逻辑添加禁用条件，例如：
            // 1. 优惠券已过期
            // 2. 订单金额不满足最低消费
            // return dayjs().isAfter(coupon.endTime);
        },

        // 优惠券状态样式
        couponStatusClass(coupon) {
            return {
                'disabled': this.isCouponDisabled(coupon),
                // 'expiring': dayjs().add(3, 'day').isAfter(coupon.endTime)
            };
        },

    },

    mounted() {
        this.loadCartData();
    },
};
</script>

<style lang="less" scoped>
@primary-color: #409EFF;
@danger-color: #F56C6C;
@border-color: #EBEEF5;

.cart-container {
    padding: 20px;
    min-height: calc(100vh - 120px);
}

.cart-table {
    margin-bottom: 30px;

    /deep/ .el-table__row:hover {
        background-color: #f5f7fa;
    }

    .product-thumb {
        width: 120px;
        height: 80px;
        border-radius: 4px;

        .image-error {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            background: #f5f5f5;
            color: #999;
        }
    }

    .price-cell {
        color: @danger-color;
        font-weight: 500;
    }
}

.pagination-wrapper {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.cart-action-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 80px;
    background: #fff;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30px;
    z-index: 1000;

    .action-left {
        display: flex;
        align-items: center;
        gap: 30px;

        .select-all-checkbox {
            /deep/ .el-checkbox__label {
                font-size: 14px;
            }
        }

        .action-btn {
            padding: 0;
            color: #666;

            &:hover {
                color: @primary-color;
            }
        }
    }

    .action-right {
        display: flex;
        align-items: center;
        gap: 40px;

        .price-summary {
            text-align: right;

            .total-items {
                color: #666;
                font-size: 12px;
            }

            .total-price {
                font-size: 18px;
                color: @danger-color;
                margin: 4px 0;
            }

            .price-tips {
                color: #999;
                font-size: 12px;
            }
        }

        .checkout-btn {
            width: 160px;
            height: 48px;
            font-size: 16px;

            &:disabled {
                opacity: 0.6;
                cursor: not-allowed;
            }
        }
    }
}

/* 二维码弹窗样式 */
.qr-code-container {
    text-align: center;
    padding: 20px;

    .qr-code-wrapper {
        img {
            width: 200px;
            height: 200px;
            margin: 0 auto;
            display: block;
            border: 1px solid #eee;
        }

        .qr-instruction {
            margin-top: 15px;
            color: #666;
            font-size: 14px;
        }

        .qr-amount {
            margin-top: 10px;
            color: @danger-color;
            font-size: 16px;
            font-weight: bold;
        }
    }

    .loading-wrapper {
        padding: 50px 0;
    }
}


.coupon-list {
    width: 100%;
}

.coupon-item {
    display: block;
    margin-bottom: 15px;

    &:last-child {
        margin-bottom: 0;
    }

    /deep/ .el-radio__input {
        position: absolute;
        top: 50%;
        right: 20px;
        transform: translateY(-50%);
    }
}

.coupon-card {
    position: relative;
    display: flex;
    border: 1px solid #EBEEF5;
    border-radius: 8px;
    padding: 15px;
    background: linear-gradient(135deg, #fff5f5, #fff);
    transition: all 0.3s;

    &.disabled {
        opacity: 0.6;
        background: #f5f5f5;
    }

    &.expiring {
        border-color: #ffba00;
        background: linear-gradient(135deg, #fff7e6, #fff);
    }
}

.coupon-header {
    width: 120px;
    text-align: center;
    border-right: 1px dashed #EBEEF5;
    padding-right: 15px;

    .amount {
        font-size: 28px;
        color: #f56c6c;
        font-weight: bold;
        line-height: 1.2;
    }

    .coupon-type {
        color: #666;
        font-size: 12px;
    }
}

.coupon-body {
    flex: 1;
    padding-left: 15px;

    .coupon-name {
        font-size: 16px;
        color: #333;
        margin-bottom: 8px;
    }

    .condition {
        color: #666;
        font-size: 12px;
        margin-bottom: 5px;
    }

    .expire {
        color: #999;
        font-size: 12px;
    }
}

.disabled .coupon-body {

    .coupon-name,
    .condition,
    .expire {
        color: #ccc;
    }
}

@media (max-width: 768px) {
    .cart-container {
        padding: 10px;
    }

    .cart-table {
        /deep/ .el-table__header-wrapper .el-checkbox {
            display: none;
        }

        .el-table-column:not(:first-child) {
            display: none;
        }
    }

    .cart-action-bar {
        height: auto;
        padding: 15px;
        flex-direction: column;
        gap: 15px;

        .action-left {
            width: 100%;
            justify-content: space-between;
        }

        .action-right {
            width: 100%;
            justify-content: space-between;
        }
    }

    /* 移动端二维码弹窗样式 */
    /deep/ .el-dialog {
        width: 90% !important;
    }
}
</style>